package com.lwl.blue.commont.config.mybatis;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.lwl.blue.commont.base.Const;
import com.lwl.blue.commont.utils.UserContextUtil;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * MyBatis-Plus 公共字段自动填充
 * - 插入时：isDelete=0、createTime、createUser、updateTime、updateUser、creatorId、updaterId
 * - 更新时：updateTime、updateUser、updaterId
 */
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        String loginUser = null;
        try {
            loginUser = UserContextUtil.getUser() == null ? null : UserContextUtil.getUser().getUserName();
        } catch (Exception ignored) {}

        this.setFieldValByName("isDelete", Const.IS_DELETE_NO, metaObject);
        this.setFieldValByName("createTime", new Date(), metaObject);
        this.setFieldValByName("updateTime", new Date(), metaObject);

        if (loginUser != null) {
            this.setFieldValByName("createUser", loginUser, metaObject);
            this.setFieldValByName("updateUser", loginUser, metaObject);
            // 兼容部分表的命名
            this.setFieldValByName("creatorId", loginUser, metaObject);
            this.setFieldValByName("updaterId", loginUser, metaObject);
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        String loginUser = null;
        try {
            loginUser = UserContextUtil.getUser() == null ? null : UserContextUtil.getUser().getUserName();
        } catch (Exception ignored) {}

        this.setFieldValByName("updateTime", new Date(), metaObject);
        if (loginUser != null) {
            this.setFieldValByName("updateUser", loginUser, metaObject);
            this.setFieldValByName("updaterId", loginUser, metaObject);
        }
    }
}


